package com.hm.oltu.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import com.hm.common.util.CommonUtil;
import com.hm.common.util.StringUtil;
import com.hm.oltu.model.Client;
import com.hm.oltu.repository.ClientRepository;
import com.hm.oltu.service.ClientService;
import com.hm.oltu.su.PageInfo;
import com.hm.oltu.vo.ClientVo;

@Service
public class ClientServiceIml implements ClientService {

	@Autowired
	private ClientRepository clientRepository;

	@Override
	public Client createClient(ClientVo clientVo) {
		Client client = new Client();
		{
			client.setClientId(StringUtil.token());
			client.setClientSecret(StringUtil.token());
			client.setClientName(clientVo.getClientName());
			client.setCreateTime(System.currentTimeMillis());
		}
		return clientRepository.save(client);
	}

	@Override
	public Client updateClient(ClientVo clientVo) {
		Client client = clientRepository.findOne(clientVo.getId());
		if (CommonUtil.isEmpty(client)) {
			client.setClientId(StringUtil.token());
			client.setClientSecret(StringUtil.token());
			client.setCreateTime(System.currentTimeMillis());
		}
		client.setClientName(clientVo.getClientName());
		return clientRepository.save(client);
	}

	@Override
	public void deleteClient(String clientId) {
		clientRepository.delete(clientId);
	}

	@Override
	public Client findOne(String id) {
		return clientRepository.findOne(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public PageInfo<ClientVo> query(int pageNo, int pageSize) {
		PageInfo<ClientVo> pageInfo = new PageInfo<ClientVo>(pageNo, pageSize);

		Pageable pageable = new QPageRequest(pageInfo.getPageNumber(), pageInfo.getPageSize());

		List<ClientVo> vos = new ArrayList<ClientVo>();
		@SuppressWarnings("rawtypes")
		Page page = clientRepository.findAll(pageable);
		page.getContent().forEach(clientModel -> {
			ClientVo clientVo = new ClientVo();
			{
				clientVo.setId(((Client) clientModel).getId());
				clientVo.setClientId(((Client) clientModel).getClientId());
				clientVo.setClientName(((Client) clientModel).getClientName());
				clientVo.setClientSecret(((Client) clientModel).getClientSecret());
				clientVo.setCreateTime(((Client) clientModel).getCreateTime());
			}
			vos.add(clientVo);
		});

		return pageInfo.execute(page, vos);
	}

	@Override
	public Client findByClientId(String clientId) {
		return clientRepository.findByClientId(clientId);
	}

	@Override
	public Client findByClientSecret(String clientSecret) {
		return clientRepository.findByClientSecret(clientSecret);
	}

}
